<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // Promise.race()  
    // Promise.all()方法用于将多个 Promise 实例，包装成一个新的 Promise 实例。
    // const p = Promise.all([p1, p2, p3]);

    // 上面代码中，只要p1、p2、p3之中有一个实例率先改变状态，p的状态就跟着改变。那个率先改变的 Promise实例的返回值(实例中存储的结果)，就传递给p


    // 小结:
    // 只看p1,p2,p3谁最先改变状态(不管成功还是失败) 


    Promise.myRace = function (arr) {  //  [p1, p2, p3]
        return new Promise(function (resolve, reject) {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];   // 每一个Promise对象
                item.then(arg => {
                    resolve(arg);
                }).catch(err => {
                    // 抛出错误
                    reject(err);
                })
            }
        })
    }

    var p1 = getNumAsync(1, 2000);
    var p2 = getNumAsync(2, 1000, false);
    var p3 = getNumAsync(3, 3000);

    // var p = Promise.myRace([p1, p2, p3]);
    var p = Promise.race([p1, p2, p3]);

    p.then(arg => {
        console.log("fulfilled", arg);
    }).catch(err => {
        console.log("rejected", err);
    })







    function getNumAsync(num, delay = 0, isFulfilled = true) {
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                isFulfilled ? resolve(num) : reject(num);
            }, delay);
        });
        return p;
    }


</script>

</html>